// 默认缓存前缀
const CACHE_PREFIX = 'medical_'

/**
 * 基础缓存工具类
 */
export class Storage {
  constructor(storage, prefix = CACHE_PREFIX) {
    this.storage = storage
    this.prefix = prefix
  }

  // 获取完整的key
  getKey(key) {
    return this.prefix + key
  }

  // 获取缓存
  get(key, defaultValue = null) {
    const rawValue = this.storage.getItem(this.getKey(key))
    if (rawValue === null) {
      return defaultValue
    }

    try {
      const { value, expire } = JSON.parse(rawValue)
      // 判断是否过期
      if (expire && expire < Date.now()) {
        this.remove(key)
        return defaultValue
      }
      return value
    } catch (error) {
      return rawValue || defaultValue
    }
  }

  // 设置缓存
  set(key, value, expire = null) {
    // 如果设置了过期时间，将过期时间转为时间戳
    const expireTime = expire ? Date.now() + expire * 1000 : null
    const data = {
      value,
      expire: expireTime
    }
    this.storage.setItem(this.getKey(key), JSON.stringify(data))
  }

  // 移除缓存
  remove(key) {
    this.storage.removeItem(this.getKey(key))
  }

  // 清空所有缓存（仅清除当前前缀的）
  clear() {
    const keys = Object.keys(this.storage)
    keys.forEach(key => {
      if (key.startsWith(this.prefix)) {
        this.storage.removeItem(key)
      }
    })
  }

  // 获取所有缓存键
  keys() {
    const keys = Object.keys(this.storage)
    return keys
      .filter(key => key.startsWith(this.prefix))
      .map(key => key.slice(this.prefix.length))
  }
}

// 本地存储
export const localCache = new Storage(localStorage)

// 会话存储
export const sessionCache = new Storage(sessionStorage)

export default {
  localCache,
  sessionCache
} 